package com.neusoft.demo9;

import java.util.*;

/**
 * 排序 List<Student> 主要有两种方式
 * 1. 让当前Student类实现Comparable接口
 * 2. 调用Collections中的sort方法
 *      sort(List<T> list, Comparator<? super T> c)  需要传递一个Comparator比较器
 */
public class Student implements Comparable<Student>{
    private String name;
    private Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    //比较此对象与指定对象的顺序。如果该对象小于、等于或大于指定对象，则分别返回负整数、零或正整数。
    //o - 要比较的对象。
    @Override
    public int compareTo(Student o) {
        if(this.age > o.getAge()) {
            return 1;
        }else if(this.age < o.getAge()) {
            return -1;
        }else {
            return 0;
        }
    }

    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();

        Student s1 = new Student("Tom",18);
        Student s2 = new Student("H胡大",28);
        Student s3 = new Student("Z周生生",8);
        Student s4 = new Student("M梅婷",100);

        list.add(s1);
        list.add(s2);
        list.add(s3);
        list.add(s4);

        //默认按照年龄排序
        Collections.sort(list);
        //遍历输出
        Iterator<Student> it = list.iterator();
        while (it.hasNext()) {
            Student student = it.next();
            System.out.println(student.getName() + "---" + student.getAge());
        }
        System.out.println("--------------------------------------------------------------");
        //倒序排序
        Comparator comparator = Collections.reverseOrder();
        Collections.sort(list,comparator);
        //遍历输出
        Iterator<Student> iterator = list.iterator();
        while (iterator.hasNext()) {
            Student student = iterator.next();
            System.out.println(student.getName() + "---" + student.getAge());
        }
        System.out.println("-------------------------------------------------------------");
        //根据姓名排序
        Collections.sort(list, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        //遍历输出结果
        Iterator<Student> its = list.iterator();
        while (its.hasNext()) {
            Student student = its.next();
            System.out.println(student.getName() + "---" + student.getAge());
        }
    }
}
